package com.wwfish.cmsui.modules.sysuser.client;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ChangeEvent;
import com.google.gwt.event.dom.client.ChangeHandler;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.ui.DockPanel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;
import com.nexustar.gwt.widgets.client.asyn.FishAsyncCallback;
import com.nexustar.gwt.widgets.client.asyn.LoadingAsyncCallback;
import com.nexustar.gwt.widgets.client.ui.form.*;
import com.nexustar.gwt.widgets.client.ui.panel.WidgetContainer;
import com.nexustar.gwt.widgets.client.ui.tab.MyTabPanel;
import com.nexustar.gwt.widgets.client.ui.textbox.FishLabelTextAreaBox;
import com.nexustar.gwt.widgets.client.ui.textbox.FishLabelTextBox;
import com.nexustar.gwt.widgets.client.ui.toolbar.ToolBar;
import com.nexustar.gwt.widgets.client.ui.toolbar.ToolItem;
import com.nexustar.gwt.widgets.client.ui.window.Message;
import com.wwfish.cms.model.sysuser.SysRoleDto;
import com.wwfish.cms.model.sysuser.SysUserDto;
import com.wwfish.cms.service.sysuser.SysUserManager;
import com.wwfish.cmsui.dashboard.client.CMSDashboard;
import com.wwfish.cmsui.modules.common.client.BaseCMSPage;
import com.wwfish.cmsui.modules.common.client.CMSPageClient;
import com.wwfish.cmsui.modules.common.client.CMSRunAsyncCallBack;
import com.wwfish.cmsui.modules.common.client.util.ServiceFactory;
import com.wwfish.cmsui.modules.sysuser.client.widget.AccessChannelTreeWidget;
import com.wwfish.cmsui.modules.sysuser.client.widget.AccessFunctionTreeWidget;
import com.wwfish.cmsui.modules.sysuser.client.widget.RoleElementWidget;

/**
 * Created by IntelliJ IDEA.
 * User: Tom
 * Date: 2010-8-18
 * Time: 10:21:50
 * To change this template use File | Settings | File Templates.
 */
public class SysUserPage extends BaseCMSPage {
    private ToolBar bar;
    private FormContainer form;
    private RoleElementWidget roleWidget;

    private Boolean isExist = false;
    private FishLabelTextBox loginName;
    private MyTabPanel bodyTab;

    @Override
    protected boolean isRunAsync() {
        return true;
    }
                                                                                
    @Override
    public void initWidgets(final DockPanel dockPanel) {
        GWT.runAsync(new CMSRunAsyncCallBack() {
            public void onSuccess() {
                initBar();

                dockPanel.setWidth("100%");
                dockPanel.add(bar, DockPanel.NORTH);
                dockPanel.setCellHeight(bar, "20px");
                dockPanel.add(initBody(), DockPanel.CENTER);

                addAsyTextBoxEvent();
                client.success(null);
            }
        });
    }

    private Widget initBody() {
        bodyTab = new MyTabPanel();
        bodyTab.setWidth("500px");
        roleWidget = new RoleElementWidget();
        bodyTab.add(getForm(), "基本信息");
        bodyTab.add(roleWidget, "权限信息");
        bodyTab.selectTab(0);
        return bodyTab;
    }

    private void initBar() {
        bar = new ToolBar();
        bar.setWidth("100%");
        ToolItem save = new ToolItem("保存");
        ToolItem back = new ToolItem("返回");
        bar.addToolItem(save);
        bar.addToolItem(back);
        save.addClickHandler(new ClickHandler() {
            public void onClick(ClickEvent event) {
                if (!form.isValid()) {
                    bodyTab.selectTab(0);
                    return;
                }
                if (isExist) {
                    ((TextBox) loginName.getUI()).setFocus(true);
                    return;
                }
                final SysUserDto user = (SysUserDto) form.getModelManger().getModel();
                final boolean isSave;
                if (user.getId() == null)
                    isSave = true;
                else
                    isSave = false;
                SysRoleDto roleDto = (SysRoleDto) roleWidget.getModelManger().getModel();
                if (roleDto == null) {
                    Message.error("请选择权限角色！");
                    bodyTab.selectTab(1);
                    return;
                }
                user.setRole(roleDto);
                ServiceFactory.invoke(SysUserManager.class.getName(), "saveAndUpdate", new Object[]{user},
                        new LoadingAsyncCallback() {
                            @Override
                            protected void success(final Object result) {
                                CMSDashboard.dispatchPage(SysUserManagePage.class.getName(), new CMSPageClient() {
                                    @Override
                                    protected void process(BaseCMSPage page) {
                                        SysUserManagePage sp = (SysUserManagePage) page;
                                        if (isSave)
                                            sp.addTableItem(result);
                                        else
                                            sp.editTableItem(result, user);
                                    }
                                });
                            }
                        });
            }
        });
        back.addClickHandler(new ClickHandler() {
            public void onClick(ClickEvent event) {
                CMSDashboard.dispatchPage(SysUserManagePage.class.getName(), null);
            }
        });
    }

    private Widget getForm() {
        WidgetContainer wrapper = new WidgetContainer();
        wrapper.setSize("100%", "100%");
        form = new FormContainer(1);
        final FishLabelTextBox name = new FishLabelTextBox("管理员名称:");
        loginName = new FishLabelTextBox("登录名:");
        final FishLabelTextBox email = new FishLabelTextBox("电子邮件:");
        final FishLabelTextBox QQ = new FishLabelTextBox("QQ:");
        final FishLabelTextBox telephone = new FishLabelTextBox("电话:");
        final FishLabelTextBox password = new FishLabelTextBox("密码:");
        final FishLabelTextBox rePassword = new FishLabelTextBox("密码确认:");


        form.addElement(new FormElement(name, new FormElementProviderAdpter() {
            public void setValue(Object object) {
                name.setValue(((SysUserDto) object).getName());
            }

            public void getValue(Object object) {
                ((SysUserDto) object).setName((String) name.getValue());
            }
        }, new IValidator[]{ValidatorCreator.require()}));
        form.addElement(new FormElement(loginName, new FormElementProviderAdpter() {
            public void setValue(Object object) {
                loginName.setValue(((SysUserDto) object).getLoginName());
            }

            public void getValue(Object object) {
                ((SysUserDto) object).setLoginName((String) loginName.getValue());
            }
        }));
        form.addElement(new FormElement(email, new FormElementProviderAdpter() {
            public void setValue(Object object) {
                email.setValue(((SysUserDto) object).getEmail());
            }

            public void getValue(Object object) {
                ((SysUserDto) object).setEmail((String) email.getValue());
            }
        }, new IValidator[]{ValidatorCreator.isEmail()}));
        form.addElement(new FormElement(telephone, new FormElementProviderAdpter() {
            public void setValue(Object object) {
                telephone.setValue(((SysUserDto) object).getTelephone());
            }

            public void getValue(Object object) {
                ((SysUserDto) object).setTelephone((String) telephone.getValue());
            }
        }, new IValidator[]{ValidatorCreator.isTelephone()}));
        form.addElement(new FormElement(QQ, new FormElementProviderAdpter() {
            public void setValue(Object object) {
                QQ.setValue(((SysUserDto) object).getQq());
            }

            public void getValue(Object object) {
                ((SysUserDto) object).setQq((String) QQ.getValue());
            }
        }));
        form.addElement(new FormElement(password, new FormElementProviderAdpter() {
            public void setValue(Object object) {
                password.setValue(((SysUserDto) object).getPassword());
            }

            public void getValue(Object object) {
                ((SysUserDto) object).setPassword((String) password.getValue());
            }
        }, new IValidator[]{ValidatorCreator.require()}));
        form.addElement(new FormElement(rePassword, new FormElementProviderAdpter() {
            public void setValue(Object object) {
                rePassword.setValue(((SysUserDto) object).getPassword());
            }

            public void getValue(Object object) {
            }
        }, new IValidator[]{ValidatorCreator.require(), new IValidator() {
            public boolean isValid(Widget ui) {
                if (rePassword.getValue() != null && !rePassword.getValue().equals(password.getValue())) {
                    rePassword.setErrorMessage("请确认密码一致！");
                    return false;
                } else {
                    rePassword.removeErrorMessage();
                    return true;
                }
            }
        }}));

        wrapper.add(form);
        return wrapper;
    }

    private void addAsyTextBoxEvent() {
        final TextBox box = ((TextBox) loginName.getUI());
        box.addChangeHandler(new ChangeHandler() {
            public void onChange(ChangeEvent event) {
                SysUserDto user = (SysUserDto) form.getModelManger().getModel();
                if (user.getId() == null)
                    ServiceFactory.invoke(SysUserManager.class.getName(), "isExitLoginName", new Object[]{box.getValue()}, new FishAsyncCallback() {
                        public void onSuccess(Object result) {
                            isExist = (Boolean) result;
                            if (isExist) {
                                ((TextBox) loginName.getUI()).setFocus(true);
                                loginName.setErrorMessage("用户名已存在！");
                            } else {
                                loginName.removeErrorMessage();
                            }
                        }
                    });
            }
        });


    }

    @Override
    protected void ddOutPageModel(Object dto) {
        isExist = false;
        if (dto == null) {
            dto = new SysUserDto();
            ((TextBox) loginName.getUI()).setReadOnly(false);
        } else
            ((TextBox) loginName.getUI()).setReadOnly(true);
        form.getModelManger().renderModel(dto);
        roleWidget.getModelManger().renderModel(((SysUserDto) dto).getRole());
        bodyTab.selectTab(0);
    }
}
